'use strict';

exports.main = async (event, context) => {
	try {
		const db = uniCloud.database();
		const collection = db.collection('data');
		
		// 获取删除参数
		const { id, ids, deleteType = 'single', olderThanDays } = event;
		
		let result;
		
		switch (deleteType) {
			case 'single':
				// 删除单条数据
				if (!id) {
					return {
						code: -1,
						message: '缺少数据ID参数'
					};
				}
				
				result = await collection.doc(id).remove();
				break;
				
			case 'multiple':
				// 删除多条数据
				if (!ids || !Array.isArray(ids) || ids.length === 0) {
					return {
						code: -1,
						message: '缺少数据ID数组参数'
					};
				}
				
				result = await collection.where({
					_id: db.command.in(ids)
				}).remove();
				break;
				
			case 'oldData':
				// 删除指定天数之前的旧数据
				if (!olderThanDays || olderThanDays <= 0) {
					return {
						code: -1,
						message: '请提供有效的天数参数'
					};
				}
				
				const cutoffTime = Date.now() - (olderThanDays * 24 * 60 * 60 * 1000);
				
				result = await collection.where({
					timestamp: db.command.lt(cutoffTime)
				}).remove();
				break;
				
			case 'all':
				// 删除所有数据（危险操作，需要确认）
				if (event.confirmDeleteAll !== true) {
					return {
						code: -1,
						message: '删除所有数据需要确认参数 confirmDeleteAll: true'
					};
				}
				
				result = await collection.where({}).remove();
				break;
				
			default:
				return {
					code: -1,
					message: '不支持的删除类型'
				};
		}
		
		if (result.deleted === 0) {
			return {
				code: -1,
				message: '未找到要删除的数据'
			};
		}
		
		return {
			code: 0,
			message: `成功删除 ${result.deleted} 条数据`,
			data: {
				deleted: result.deleted
			}
		};
		
	} catch (error) {
		console.error('删除数据失败:', error);
		return {
			code: -1,
			message: '数据删除失败',
			error: error.message
		};
	}
};